/* constants */
import { FORM_FIELD_TEXTAREA_MAX_LENGTH } from '@src/model/const/Number.ts'
/* enum */
import { FieldTypeMappingEnum } from '@model/enum/FieldMappingEnum.ts'
/* model */
import FormStyle from '@model/form/FormStyle.ts'
import { ShbFormUtilInitOptions } from '@model/biz/Form' 
/* utils */
import { assign, cloneDeep } from 'lodash'
import { isNumber, isPlanObject, isUndefined, isEmpty } from '@src/util/type'
import FormField from '@src/component/form/FormField'
export * from '@src/component/form/util/validate'
import { allAmountFieldNameList, contractAmountFieldNameList, CURRENCY_SUFFIX } from '@src/util/currency';
/**api */
import { getRichTextContent , getImRichTextContent} from '@src/api/SystemApi'

/* service */
import { isGroupField, isQualityRuleField, isCurrencyField } from '@service/FieldService.ts'
import { convertQualityRuleRemoteDataToFormQualityRuleFieldValue } from '@service/QualityRuleService.ts'
import { t } from '@src/locales'
import { SELECT_OPTION_MAX } from '@src/component/form/config'
import { getTenantConfig } from '@src/api/ProductV2Api';

import { getRootWindow } from '@src/util/dom';

import { Message } from 'element-ui';

const BASE_EXPAND_FORMTYPE = ['idcard']

const DEFAULT_PLACEHOLDER = {
  text: t('common.placeholder.input2'),
  description: t('common.placeholder.limitInput', {limit: FORM_FIELD_TEXTAREA_MAX_LENGTH}),
  textarea: t('common.placeholder.limitInput', {limit: FORM_FIELD_TEXTAREA_MAX_LENGTH}),
  number: t('common.placeholder.inputNumber'),
  customerAddress: t('common.placeholder.selectSomething', {0: t('common.form.type.customerAddress')}),
  relationCustomer: t('common.placeholder.searchByCustomerInfo'),
  relationProduct: t('common.placeholder.searchByProductInfo'),
  user: t('common.placeholder.selectMember'),
  date: t('common.base.date'),
  datetime: `${t('common.base.date')} + ${t('common.base.time')}`,
  select: t('common.placeholder.select'),
  location: t('common.placeholder.input2'),
  phone: t('common.placeholder.inputPhone2'),
  code: t('common.placeholder.mobileScanOrInput'),
  serviceProviderQualification: t('common.placeholder.selectProviderQuality'),
  engineerQualification: t('common.placeholder.selectEngineerQuality'),
  address: t('common.placeholder.selectAddress'),
  email: t('common.placeholder.inputEmail'),
  formula: t('common.placeholder.input2')
}

/**
 * @description 获取默认的占位符
 * ! 目前特殊处理的是 maxlength 最大长度
 * @returns {String} 占位符
*/
export function getDefaultPlaceholder(formType = '', maxlength, fieldName) {
  if (isNumber(maxlength)) {
    return t('common.placeholder.limitInput', {limit: maxlength})
  }
  if (formType == 'phone' && ['phone', 'lmPhone'].includes(fieldName)) return t('common.placeholder.phoneOrEmail')
  if (formType == 'email' && ['email', 'lmEmail'].includes(fieldName)) return t('common.placeholder.emailOrPhone')

  return DEFAULT_PLACEHOLDER[formType] || ''
}

export function groupField(fields, form, showHiddenField) {
  let newArr = [];
  let preIndex = 0;

  expandField(fields)
    // 隐藏不显示逻辑项
    .filter(item => showHiddenField ? item : !fieldSettingIsHidden(item) && !isHiddenField(item, form, fields, false))
    // 根据分割线分组
    .forEach((f, index, filterArr) => {
      if (f.formType === 'separator') {
        newArr.push(filterArr.slice(preIndex, index));
        preIndex = index;
      }

      if (index === filterArr.length - 1) {
        newArr.push(filterArr.slice(preIndex));
      }
    });

  return newArr;
}
/**
 * 不分多个组
 * @param {*} fields 
 * @param {*} form 
 * @param {*} showHiddenField 
 */
export function noGroup(fields, form, showHiddenField) {
  let newArr = [];
  let preIndex = 0;

  expandField(fields)
    // 隐藏不显示逻辑项
    .filter(item => showHiddenField ? item : !isHiddenField(item, form, fields, false))
    // 根据分割线分组
    .forEach((f, index, filterArr) => {
      if (index === filterArr.length - 1) {
        newArr.push(filterArr.slice(preIndex));
      }
    });

  return newArr;
}

// 是否隐藏分割线
export function isHiddenSeparator(groups, form, fields, fieldName, isSmooth) {
  // 当前分割线分组字段，不包含分割线
  let currentGroup = []
  groups.forEach(group => {
    group.forEach(item => {
      if (item.fieldName == fieldName) {
        currentGroup = group.filter(item => item.formType != 'separator')
      }
    })
  })
  const allIsHiddenField = currentGroup.every(item => isHiddenField(item, form, fields, isSmooth))
  // 当前分割线分组字段都不显示时，分割线不显示
  return allIsHiddenField
}

/**
 * 将设计器输出的字段格式转换成后端可接受的类型 
 * 注意： 需要在提交时补全以下字段，如果有的话：
 *  tableName、templateId、templateName
 */
export function toField(fields){
  return fields.map(field => FormField.toField(field))
}

/** 将后端字段转换成设计器可接受的字段 */
export function toFormField(fields){
  return migration(fields).map(item => FormField.fromField(item));
}

/** 迁移旧有字段至新类型，主要用于兼容客户、产品旧字段 */
export function migration(fields) {
  return fields.map(field => {
    // 多选格式调整
    if (field.formType == FieldTypeMappingEnum.SelectMulti) {
      if (!field.setting) {
        field.setting = { isMulti: true, dataSource: [] }
      }
      field.formType = FieldTypeMappingEnum.Select
      field.setting.isMulti = true
    }

    return field
  })
}

/** 是否为多选类型 */
export function isMultiSelect(field = {}) {
  let setting = field.setting || {}

  return (
    (field.formType == FieldTypeMappingEnum.Select && setting.isMulti)
    || field.formType == FieldTypeMappingEnum.SelectMulti
    || field.formType == 'engineerQualification'
  )
}

/** 是否为单选类型 */
export function isSelect(field){
  let setting = field.setting || {};

  return ((field.formType == 'select' || field.formType == 'quality_rule' ) && !setting.isMulti)
    || field.formType == 'level'
    || field.formType == 'serviceContent'
    || field.formType == 'serviceType'
    || field.formType == 'solveStatus'
    || field.formType == 'serviceProviderQualification'
    || field.formType == 'engineerQuality'
    || field.formType == 'provideQuality'
}

/** 是否为质保 */
export function isQuality(field){
  return field.formType == 'quality';
}

/** 是否为级联选择器 */
export function isCascader(field){
  return field.formType == 'related_catalog'
}

/** 是否为有默认值的级联选择器 */
export function isHaveDefaultValueCascader(field) {
  return field.formType == 'cascader'
}

/** 是否为日期类型 yyyy-MM-dd */
export function isDate(field){
  let setting = field.setting;

  return field.formType == 'date'
    || ((field.formType == 'planTime' || field.formType == 'planStartTime' || field.formType == 'planEndTime') && (setting != null && setting.dateType == 'date'));
}

export function isDateField(field) {
  const setting = field?.setting || {}
  const formType = field?.formType
  const isPlanTime = ['planTime', 'planStartTime', 'planEndTime'].includes(field.formType)
  const isDateType = formType == 'date'
  return isDateType || isPlanTime
}

/** 是否为日期时间类型 yyyy-MM-dd HH:mm:ss */
export function isDatetime(field){
  let setting = field.setting;

  return field.formType == 'datetime'
    || ((field.formType == 'planTime' || field.formType == 'planStartTime' || field.formType == 'planEndTime') && (setting == null || setting.dateType != 'date'));
}

export function isDatetimeField(field) {
  const setting = field?.setting || {}
  const formType = field?.formType
  const isPlanTime = ['planTime', 'planStartTime', 'planEndTime'].includes(field.formType)
  const isDatetimeType = formType == 'datetime'
  return isDatetimeType || isPlanTime
}

/** 是否为说明信息类型 */
export function isInfo(field) {
  return field.formType === 'info';
}

/** 构建placeholder */
export function genPlaceholder(field, defaultText = ''){
  let text = '';
  if(field.isNull == 0) {
    text += (isSelect(field) || isMultiSelect(field) || isCascader(field)) ? `[${t('common.base.required')}] ` : `[${t('common.base.isRequire')}] `
  }

  // let placeholder = field.placeholder || field.placeHolder;
  // if(placeholder) return text + placeholder;

  let key = field.formType;
  if(isDate(field)) key = 'date';
  if(isDatetime(field)) key = 'datetime';
  if(isSelect(field) || isMultiSelect(field) || field.formType == 'cascader') key = 'select';

  return text + (getDefaultPlaceholder(key, field?.maxlength, field.fieldName) || '');
}

// 不需要默认值
const withoutDefaultFormType = new Set(['info', 'separator', 'customer', 'eventNo', 'taskNo'])

const defaultValueMap = {
  'link': {}, // 超链接的默认值初始化为对象
  'customerAddress': {}, 
  'address': {},
  'faultLibrary': {}, // 故障库
  'attachment': [],
  'taskAttachment': [],
  'receiptAttachment': [],
  'materialReturn': [], // 物料返还字段
  'materialVerifyEliminate': [], // 物料核销字段
  'relationMaterials': [], // 产品关联物料
  'related_catalog': [], // 
}
/**
 * @description 初始化所有字段的初始值
 * @param {Field[]} fields 字段列表
 * @param {Record<string, any>} origin 原始值
 * @param {Function | undefined} callback 回调函数
 * @param {ShbFormUtilInitOptions | undefined} options 配置项
 * @returns {Record<string, any>} 初始化后的值
 */
export function initialize(fields = [], origin = {}, callback = undefined, options = new ShbFormUtilInitOptions()) {
  
  let result = typeof callback == 'function' ? callback(fields, origin) : origin;
  
  expandField(fields).filter(field => field.formType !== 'info' && field.formType !== 'separator').forEach(field => {
    
    const { formType, fieldName, tableName } = field
    const setting = field.setting || {}
    const dataSource = setting.dataSource || []
    // 跳过
    if(withoutDefaultFormType.has(formType)) return;

    // 如果已经存在值 则无需初始化 置顶
    if(result[fieldName]) return;
    
    let defaultValue = (options.isUseFieldDefaultValue && field.defaultValue) || defaultValueMap[formType] || '';
    let { defaultValueConfig } = setting;
    
    let { isCurrentDate, isCurrentUser } = defaultValueConfig || {};
    let dateType = setting.dateType || 'yyyy-MM-dd';
    
    // 屏蔽工单上单选里不存在默认值
    if(isSelect(field) && dataSource.indexOf(defaultValue) < 0) defaultValue = '';
    
    if(isMultiSelect(field) || isSubForm(field)) {
      // 默认值是 [] -- 多选和附件的默认值初始化为空数组
      defaultValue = []
    } else if(formType == 'cascader'){
      // 多级选择，需要拆解默认值
      let cascaderDefaultValue = [];
      if(defaultValue) cascaderDefaultValue = defaultValue.split(',')
    
      defaultValue = cascaderDefaultValue;
    } else if(formType == 'user') {
      // 人员字段初始化
      let { isMultiple } = setting || {};
      
      // 当前登录账户数据
      let { userId, displayName, staffId, head } = window.parent.loginUser || {};
      
      // 默认当前登录账户
      if (isCurrentUser == 1 && userId && options.isUseFieldDefaultValue) {
        let loginUser = { userId, displayName, staffId, head };
        defaultValue = isMultiple == 1 ? [loginUser] : loginUser;
      } else {
        defaultValue = isMultiple == 1 ? [] : {};
      }
    }

    // 子表单表单
    if (isSubForm(field)) {
      defaultValue = [];
    }
    
    // 物料返还字段
    if (formType == 'materialReturn') {
      defaultValue = []
    }
    
    // 物料核销字段
    if (formType == 'materialVerifyEliminate') {
      defaultValue = []
    }

    // 故障库
    if (formType == 'faultLibrary') {
      defaultValue = {}
    }
    
    // 产品关联物料
    if (formType == 'relationMaterials') {
      defaultValue = []
    }

    // 关联服务项目
    if (formType == 'relatedServiceItem') {
      defaultValue = []
    }

    // 结算货币字段
    if (formType == 'currencyType') {
      defaultValue = setting.defalutCurrency || 'CNY'
    }

    // 备件返还
    if (formType == 'sparePartsReturnExpense') {
      defaultValue = []
    }

    // 物流组件
    if (formType === 'logistics') {
      const newValue = {
        no: '',
        company: null
      };
      
      const logisticsDefaultValue = result[fieldName] || [newValue];
      
      defaultValue = options.isUseFieldDefaultValue ? logisticsDefaultValue : [newValue];
    }

    if((tableName === 'contract' || tableName === 'project') && formType === 'customerAddress'){
      // 覆盖 customerAddress 默认值
      defaultValue = []
    }
    
    // 来自表单的值，用于编辑时初始化值
    let attribute = origin.attribute || {};
    let formData = field.isSystem === 1 ? origin[fieldName] : attribute[fieldName];
    
    // 多选改单选,若原来有值则保留第一个
    if(isSelect(field) && Array.isArray(formData)) {
      formData = (formData && formData.length >= 1) ? formData[0] : '';
    }
    // 单选改多选，将原值加入数组
    if(isMultiSelect(field) && !Array.isArray(formData)) {
      formData = formData ? [formData] : [];
    }
    // 日期 若设置默认值，将系统时间设为默认值
    if(
      formType == 'date' 
      && isPlanObject(defaultValueConfig)
      && Object.keys(defaultValueConfig).length > 0
      && isCurrentDate == 1
      && options.isUseFieldDefaultValue
    ) {
      
      // 是否为年月日时
      const isDateHour = Boolean(setting?.isDateHour)
      // 如果是年月日时，将默认值设置为当前时间，且时间为整点，如 2021-01-01 00:00:00，分钟和秒数为0
      if (isDateHour) {
        defaultValue = new Date().setMinutes(0, 0, 0)
      } else {
        defaultValue = +new Date();
      }
      
    }
    
    // 关联工单表单默认值设为数组
    if(formType == 'related_task' && !Array.isArray(formData)) {
      defaultValue = [];
    }

    // 关联客户默认值设置为数组
    if(formType == 'related_customers' && !Array.isArray(formData)) {
      defaultValue = [];
    }

    // 合同服务部门
    if ((formType == 'tags' || formType == 'linkman') && (field.tableName === 'contract' || field?.tableName === 'project')) {
      defaultValue = [];
    }
    
    // 客户服务部门
    if (formType == 'select' && fieldName == 'tags') {
      defaultValue = [];
    }
    
    if (formType == 'style') {
      defaultValue = new FormStyle()
    }
    
    if(formType === 'tagLabel' || formType === 'imageDisplay') {
      defaultValue = [];
    }

    if(formType === 'projectProduct' || formType === 'projectCustomer') {
      defaultValue = [];
    }
    
    // 分组字段
    if (isGroupField(field)) {
      formData = initialize(field.groupFields, formData)
    }
    
    // 质保规则字段
    if (isQualityRuleField(field)) {
      const qualityRuleRemoteData = formData || origin
      formData = convertQualityRuleRemoteDataToFormQualityRuleFieldValue(qualityRuleRemoteData)
    }

    // 货币金额字段
    if (isCurrencyField(field)) {
      defaultValue = { number: field.defaultValue || '', currency: field?.setting?.defaultCurrency || 'CNY' };
    }

    // 货币金额字段
    if (contractAmountFieldNameList.includes(fieldName)) {
      result[fieldName + CURRENCY_SUFFIX] = field?.setting?.defaultCurrency || 'CNY';
    }

    // 连接器
    if (formType === FieldTypeMappingEnum.Connector) {
      defaultValue = [];
    }

    // 服务备注产品
    if (formType === 'remarkProduct') {
      defaultValue = [];
    }

    
    result[fieldName] = formData == null ? defaultValue : formData;
  });


  return assign({}, origin.attribute, result);

}

/**
 * 检测是否为隐藏字段
 * @param {*} field - 待检测的字段
 * @param {*} form - 表单值
 * @param {*} allFields - 所有字段
 * @param {string} isSmooth - 是否平整。 值为true时，直接从form对象上取值；值为false时，根据字段isSystem取值
 */
export function isHiddenField(field, form, allFields, isSmooth = true){
  let map = {};

  for(let i = 0; i < allFields.length; i++) {
    map[allFields[i].fieldName] = allFields[i];
  }
  
  return _isHiddenField(field, form, map, isSmooth);
}

export function _isHiddenField(field, form, fieldMap, isSmooth){
  if(!field) return true;
  
  let setting = field.setting || {};
  let dependencies = setting.dependencies;
  
  // 无依赖不隐藏
  if(null == dependencies || Object.keys(dependencies).length == 0) return false;
  
  let isHidden = true;
  
  for(let prop in dependencies){
    if (!isHidden) break;
    
    let val = getHiddenFieldValue(prop, form, fieldMap, isSmooth)
    let dep = dependencies[prop];
    if(Array.isArray(dep) && dep.length > 0 && dep.indexOf(val) >= 0) isHidden = false;
    
    // 先判定依赖字段是否显示
    let depField = fieldMap[prop];
    if(depField == null) isHidden = true;
    if(_isHiddenField(depField, form, fieldMap, isSmooth)) isHidden = true;
  }
  
  return isHidden;
}

/* 是否为可见字段 */
export function isVisibleField(field, onlyVisible = false) {
  let { isHidden = 0, isVisible = 1, } = field;
  if(Reflect.has(field, 'subFormFieldList') && field.subFormFieldList && field.subFormFieldList.length > 0) {
    field.subFormFieldList = field.subFormFieldList.filter(field=> isVisibleField(field, onlyVisible));
  }
  return onlyVisible ? isVisible : !isHidden && isVisible;
}

function getHiddenFieldValue(prop, form, fieldMap, isSmooth){
  let field = fieldMap[prop];
  return getValue(field, form, isSmooth)
}

/**
 * 根据字段取值
 * @param {*} field - 字段
 * @param {*} form - 表单对象
 * @param {*} isSmooth - 是否平整。 值为true时，直接从form对象上取值；值为false时，根据字段isSystem取值
 */
export function getValue(field, form, isSmooth = false){
  if(null == field) return null;
  let fieldName = field.fieldName;

  // 直接从form上取值，适用于FormBuilder
  if(isSmooth) return form[fieldName];

  // 客户负责人
  if(field.tableName == 'customer' && fieldName == 'manager'){
    return {userId:form.customerManager, displayName: form.customerManagerName}
  }

  // 产品负责人
  if(field.tableName == 'product' && fieldName == 'productManager'){
    return {userId:form.productManager, displayName: form.productManagerName}
  }

  // 系统字段
  if(field.isSystem == 1) return form[fieldName];

  // 自定义字段
  let attribute = form.attribute || {};
  return attribute[fieldName];
}

export function isMultiField(field) {
  if(!field) return false;

  const isMulti = field?.setting ? field.setting.isMulti || field.setting.isMultiple : false;
  return isUndefined(isMulti) ? false : Boolean(isMulti);
}

/**
 * 检测是否为子表单
 * @param {*} field - 待检测的字段
 */
export function isSubForm(field) {
  let { formType, setting } = field;
  return (
    formType === 'subForm' || setting?.isSubForm
  );
}

export function expandField(fields) {
  return fields.reduce((result, field)=> {
    if(BASE_EXPAND_FORMTYPE.includes(field.formType)) {
      const subFields = field?.setting?.settingFields?.filter(subField=> subField?.setting?.show).map(subField=> {
        subField.setting.parentFieldName = field.fieldName
        subField.tableName = field?.tableName || ''
        return subField
      })
      subFields && result.push(...subFields)
    } else {
      result.push(field)
    }
    return result
  }, [])
}

export function filterFields(fields, isFromSubForm = false) {
  if (!fields) return;
  return (
    fields
      .map(field => {
        field.subFormFieldList = filterFields(
          field.subFormFieldList,
          isSubForm(field)
        );

        return field;
      })
      // 过滤分割线、说明信息、隐藏字段
      .filter(field => !field.isHidden)
      // 子表单中不显示的关联字段
      .filter(field => {
        let { isSystem, setting = {} } = field;
        return (
          !isFromSubForm ||
          !isSystem ||
          (isSystem && (setting.isShow || setting.isShow == undefined))
        );
      })
  );
};

export async function getSelectOptionMax(params) {
  const { data } = await getTenantConfig(params);
  return !isEmpty(data) ? data[0]?.configNumValue || SELECT_OPTION_MAX : SELECT_OPTION_MAX;
}

/** 是否为是否销售的关联的加个 */
export function isAmountCurrencyFieldName(field) {
  return allAmountFieldNameList.includes(field.fieldName);
}

export async function bgiPrivateVerification(selectList, keys = { AddressKey: 'address', CountryKey: 'country', formType :'' }) {
  const { AddressKey, CountryKey, formType } = keys;

  return new Promise((resolve, reject) => {
    // 只有修改时间走这个流程
    let timeRegex = /time/i;
    let dateRegex = /date/i;
    if (!timeRegex.test(formType) && !dateRegex.test(formType)) {
      resolve();
      return
    }
    // 只有华大基因走这个逻辑
    const RootWindow = getRootWindow(window);
    const bgiPrivate = RootWindow.grayAuth?.bgiPrivate || false;
    if (bgiPrivate && selectList?.length) {
      let countrys = [];
      selectList.forEach(item => {
        const country = item?.[AddressKey]?.[CountryKey] || '';
        // 已有数据和空数据不记录在内
        if (!countrys.includes(country) && country) {
          countrys.push(country);
        }
      });
      if (countrys.length > 1) {
        Message.error(t('common.placeholder.notBelongingCountry'));
        reject();
      } else {
        resolve();
      }
    } else {
      resolve();
    }
    resolve();
  });
}

/**
 * 获取未开通（没购买或者没灰度等）但是要显示在页面上的控件
 * @param {*} mode 设计器模式
 * @param {*} filterType 被过滤的方式 1: 被role_auth过滤掉的 fieldControls: 被fieldControls过滤掉的
 */
export const getActivateControlFields = (mode, filterType) => {
  // displayName: 没啥用，当简介用，不需要翻译。
  const task_role_auth_fields = [
    {
      formType: 'planStartTime',
      displayName: '计划开始时间',
      isSystem: 1,
    },
    {
      formType: 'planEndTime',
      displayName: '计划完成时间',
      isSystem: 1,
    },
    {
      formType: 'currency',
      displayName: '货币金额',
      isSystem: 1,
    },
  ]

  const maps = {
    'task': {
      role_auth : task_role_auth_fields,
      fieldControls: [
        ...task_role_auth_fields,
        {
          formType: 'faultLibrary',
          displayName: '故障库',
          isSystem: 1,
        },
        {
          formType: 'quality',
          displayName: '质保信息',
          isSystem: 1,
        },
        {
          formType: 'serviceProviders',
          displayName: '服务商',
          isSystem: 1,
        },
        {
          formType: 'serviceProviderQualification',
          displayName: '服务商等级',
          isSystem: 1,
        },
      ]
    },
    'projectType': {
      fieldControls : [
        {
          formType: 'connector',
          displayName: '连接器',
        },
      ]
    }
  }

  return maps?.[mode]?.[filterType] ?? [];
};


/**
 * @des 以下的表单类型是不需要做表单分列的
 */
export const needRowForOneEnum = ['connector', 'richtext', 'separator', 'info', 'quality_info', 'serviceProviders', 'relationForm', 'customer', 'address', 'logistics', 'subCertifications', 'subSucCase', 'quality_rule', 'materialsBill', 'product', 'subSparePart', 'productWarrantyService']

/**
 * @des 以下的表单类型是不需要外层margin
 */
export const dontNeedMarginForBox = ['address', 'logistics']

/**
 * @des 以下的表单类型是需要内层padding
 */
export const needPaddingForBox = []

/**
 * @des 以下的表单类型是不需要做表单详情分列的
 */
export const needRowForOneEnumInView = ['connector', 'richtext', 'separator', 'info', 'quality_info', 'serviceProviders', 'relationForm', 'logistics', 'quality', 'subCertifications', 'subSucCase', 'product', 'productWarrantyService']

export function getformItemClass(field, isSlot = false, formCellCount){
  let formItemClass = [`bbx-form-item-${field.formType}`];
  if(field.formType == 'attachment') formItemClass.push('form-item-attachment')
  if(field.isCellLast){
    formItemClass.push('bbx-form-item-last')
  }
  if(field?.formType && !needRowForOneEnum.includes(field.formType) && !isSlot){
    formItemClass.push('bbx-form-cell-item')
  }else{
    if(field.formType === 'connector'){
    
      if(field.setting?.selectType === 2){
        formItemClass.push('bbx-form-item')
      }else{
        formItemClass.push('bbx-form-cell-item')
      }
    }else{
      formItemClass.push('bbx-form-item')
    }
    
  }
  formItemClass.push(`bbx-from-item-cell-box-${formCellCount}`)
  if(formCellCount > 1){
    if(!dontNeedMarginForBox.includes(field.formType)){
      formItemClass.push('mar-r-12')
    }
    if(needPaddingForBox.includes(field.formType)){
      formItemClass.push('pad-r-12')
    }
    
  }
  
  return formItemClass.join(' ')
}

/**
 * 相关钉钉hover问题 webkit内核原因 sett https://github.com/SortableJS/Vue.Draggable/issues/677
 */
export const formPreviewCompHoverMethodsEffect = {
  removeElClass: function(elements, elClass) {
    elements = [].slice.call(elements);

    for (const el of elements) {
      el.classList.remove(elClass);
    }

    return elements;
  },


  setHoverEffect: function  (event) {
    const childList = formPreviewCompHoverMethodsEffect.removeElClass(event.currentTarget.parentElement.children, 'hovered');
    if(!childList.some((child) => child.classList.contains('sortable-chosen')) ) {
      event.currentTarget.classList.add('hovered');
    }
  },

  hideHovered: function  (event) {
    const item = event.currentTarget;
    formPreviewCompHoverMethodsEffect.removeElClass(item.parentElement.children, 'hovered');
  }

};
/** 获取build和view富文本的值 */
export async function initRichTextContent(fields = [], form = {}, defaultApi = true ) {
  try {
    // 兼容服务备注
    const getRichTextContentApi = defaultApi ? getRichTextContent : getImRichTextContent;
    const formDate = cloneDeep(form);
    const richtextObj = {};
    const richFields = fields.filter(item => item.formType === 'richtext' && item.isSystem == 0);
  
    for (const field of richFields) {
      const { isSystem, fieldName } = field;
      const id = formDate?.attribute?.[fieldName];
      
      if (id) {
        richtextObj[id] = fieldName;
      }
    }
    
    const richtextIds = Object.keys(richtextObj) || [];
        
    if (richtextIds.length) {
      const { success, result = [] } = await getRichTextContentApi({ids: richtextIds});

      if (success) {
        result.forEach((item, index) => {
          const key = richtextIds[index];
          const fieldName = richtextObj[key];
          formDate.attribute[fieldName]= item.content;
        });
      }
    }
    return formDate;
  } catch (error) {
    console.warn(error, 'error try catch');
  }
  
}


/**
 * Description 目前仅仅给js代码块用因为是从paas中拷贝过来的
 * @returns {any}
 */
export const isInSubForm = () => {
  return false
}


export function fieldSettingIsHidden(field) {
  return !!(field.setting?.hidden || false);
}
